package com.dc.sr.controller;

import com.dc.sr.util.RedisLock;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 测试控制器
 *
 * @author duchao
 */
@Slf4j
@RestController
@RequestMapping("/test")
public class TestController {

    private final RedisLock redisLock;
    private static final String ORDER_LOCK_PREFIX = "order:lock:";
    private static int count = 0;

    public TestController(RedisLock redisLock) {
        this.redisLock = redisLock;
    }

    @GetMapping
    public void testLock(){
        final String lockKey = ORDER_LOCK_PREFIX + 1;
        ExecutorService newFixedThreadPool = Executors.newFixedThreadPool(10);
        for (int i = 0; i < 10; i++) {
            newFixedThreadPool.execute(()->{
                try {
                    Boolean lock = redisLock.lock(lockKey,1*1000L, 5 * 60 * 1000L);
                    if (lock) {
                        //模拟业务处理
                        count();
                    }
                } catch (Exception e){
                    log.error("业务异常",e);
                } finally {
                    redisLock.unLock(lockKey);
                }
            });
        }
    }

    void count() {
        count = count + 1;
        log.info("计数：" + count);
    }
}
